import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:desktop_drop/desktop_drop.dart';
import 'dart:io';
import '../models/map_models.dart';
import '../providers/map_editor_provider.dart';
import '../widgets/map_view.dart';
import '../widgets/tile_palette.dart';
import '../widgets/layer_panel.dart';
import '../services/file_service.dart';
import '../services/tmx_parser.dart';
import '../widgets/image_import_dialog.dart';

class MainScreen extends StatefulWidget {
  const MainScreen({super.key});

  @override
  State<MainScreen> createState() => _MainScreenState();
}

class _MainScreenState extends State<MainScreen> {
  bool _showLayerPanel = true;
  bool _isDragOver = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('地图编辑器'),
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
      ),
      body: DropTarget(
        onDragDone: (detail) => _handleDroppedFiles(detail),
        onDragEntered: (detail) {
          setState(() {
            _isDragOver = true;
          });
        },
        onDragExited: (detail) {
          setState(() {
            _isDragOver = false;
          });
        },
        child: Stack(
          children: [
            // 主要内容
            Consumer<MapEditorProvider>(
              builder: (context, provider, child) {
                return Column(
                  children: [
                    // 顶部工具栏，对应原Android的HorizontalScrollView
                    _buildToolbar(context, provider),
                    // 分割线
                    Container(
                      height: 2,
                      color: const Color(0xFF089FA1),
                    ),
                    // 主要内容区域
                    Expanded(
                      child: Row(
                        children: [
                          // 地图和图块区域
                          Expanded(
                            child: Column(
                              children: [
                                // 地图显示区域，对应原Android的MapView
                                Expanded(
                                  flex: 3, // layout_weight="10"对应的比例
                                  child: Container(
                                    color: const Color(
                                        0xFF5C5C5C), // 对应原Android的background
                                    child: const MapView(),
                                  ),
                                ),
                                // 图块选择区域，对应原Android的GridView
                                const TilePalette(),
                              ],
                            ),
                          ),

                          // 图层面板
                          if (_showLayerPanel) const LayerPanel(),
                        ],
                      ),
                    ),
                  ],
                );
              },
            ),

            // 拖拽反馈覆盖层
            if (_isDragOver)
              Container(
                color: Colors.blue.withAlpha(50),
                child: const Center(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Icon(
                        Icons.cloud_upload_outlined,
                        size: 64,
                        color: Colors.blue,
                      ),
                      SizedBox(height: 16),
                      Text(
                        '拖拽文件到此处',
                        style: TextStyle(
                          fontSize: 24,
                          fontWeight: FontWeight.bold,
                          color: Colors.blue,
                        ),
                      ),
                      SizedBox(height: 8),
                      Text(
                        '支持 TMX 地图文件和 PNG/JPG 图片文件',
                        style: TextStyle(
                          fontSize: 16,
                          color: Colors.blue,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
          ],
        ),
      ),
    );
  }

  // 处理拖拽的文件
  Future<void> _handleDroppedFiles(DropDoneDetails detail) async {
    final messenger = ScaffoldMessenger.of(context);
    final provider = Provider.of<MapEditorProvider>(context, listen: false);

    for (final file in detail.files) {
      final filePath = file.path;
      final extension = filePath.toLowerCase().split('.').last;

      try {
        if (extension == 'tmx') {
          // 打开TMX地图文件
          await _openTmxFile(filePath, provider);
          if (mounted) {
            messenger.showSnackBar(
              SnackBar(
                  content:
                      Text('地图文件已打开: ${FileService.getFileName(filePath)}')),
            );
          }
        } else if (['png', 'jpg', 'jpeg', 'gif', 'bmp'].contains(extension)) {
          // 导入图片作为图块集
          await _importImageFile(filePath, provider);
        } else {
          if (mounted) {
            messenger.showSnackBar(
              SnackBar(content: Text('不支持的文件格式: .$extension')),
            );
          }
        }
      } catch (e) {
        if (mounted) {
          messenger.showSnackBar(
            SnackBar(content: Text('处理文件失败: $e')),
          );
        }
      }
    }
  }

  // 打开TMX地图文件
  Future<void> _openTmxFile(String filePath, MapEditorProvider provider) async {
    await provider.openMap(filePath);
  }

  // 导入图片文件作为图块集
  Future<void> _importImageFile(
      String imagePath, MapEditorProvider provider) async {
    if (!provider.hasMap) {
      // 如果没有地图，先提示用户创建地图
      if (mounted) {
        final shouldCreate = await showDialog<bool>(
          context: context,
          builder: (context) => AlertDialog(
            title: const Text('需要创建地图'),
            content: const Text('导入图块前需要先创建一个地图。是否要创建默认地图？'),
            actions: [
              TextButton(
                onPressed: () => Navigator.of(context).pop(false),
                child: const Text('取消'),
              ),
              ElevatedButton(
                onPressed: () => Navigator.of(context).pop(true),
                child: const Text('创建'),
              ),
            ],
          ),
        );

        if (shouldCreate == true) {
          provider.createNewMap(
              width: 50, height: 50, tileWidth: 32, tileHeight: 32);
        } else {
          return;
        }
      }
    }

    // 分析图片并自动导入为图块集
    try {
      final imageInfo = await FileService.analyzeImageFile(imagePath);
      final suggestion = FileService.suggestTileSetFromImage(imageInfo, 32, 32);

      if (suggestion.tileCount > 0) {
        // 计算firstGid
        int firstGid = 10; // 基础图块占用1-9
        for (final tileSet in provider.currentMap!.tileSets) {
          final maxGid = tileSet.firstGid + tileSet.tileCount;
          if (maxGid >= firstGid) {
            firstGid = maxGid;
          }
        }

        final tileSet = TileSet(
          name: suggestion.name,
          imagePath: suggestion.imagePath,
          tileWidth: suggestion.tileWidth,
          tileHeight: suggestion.tileHeight,
          tileCount: suggestion.tileCount,
          columns: suggestion.columns,
          firstGid: firstGid,
        );

        provider.addTileSet(tileSet);

        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
                content:
                    Text('图块集已导入: ${tileSet.name} (${tileSet.tileCount}个图块)')),
          );
        }
      }
    } catch (e) {
      throw Exception('导入图片失败: $e');
    }
  }

  Widget _buildToolbar(BuildContext context, MapEditorProvider provider) {
    return Container(
      height: 60,
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      child: SingleChildScrollView(
        scrollDirection: Axis.horizontal,
        child: Row(
          children: [
            // 当前选中图块预览，对应原Android的selectImage
            Container(
              width: 42,
              height: 42,
              margin: const EdgeInsets.only(right: 8),
              decoration: BoxDecoration(
                border: Border.all(color: Colors.grey),
                borderRadius: BorderRadius.circular(4),
              ),
              child: _buildSelectedTilePreview(provider),
            ),

            // 文件菜单，对应原Android的menuFile
            _buildMenuButton(
              context,
              '文件',
              [
                _MenuItem(
                    '新建', Icons.description, () => _showNewMapDialog(context)),
                _MenuItem(
                    '打开', Icons.folder_open, () => _openMap(context, provider)),
                _MenuItem('保存', Icons.save, () => _saveMap(context, provider)),
                _MenuItem(
                    '另存为', Icons.save_as, () => _saveAsMap(context, provider)),
                _MenuItem('导出为文本', Icons.text_snippet,
                    () => _exportAsText(context, provider)),
                _MenuItem('导出为数组', Icons.code,
                    () => _exportAsArray(context, provider)),
                _MenuItem(
                    '退出', Icons.exit_to_app, () => Navigator.of(context).pop()),
              ],
            ),

            // 编辑菜单，对应原Android的menuEdit
            _buildMenuButton(
              context,
              '编辑',
              [
                _MenuItem('撤销', Icons.undo,
                    provider.canUndo ? () => provider.undo() : null),
                _MenuItem('恢复', Icons.redo,
                    provider.canRedo ? () => provider.redo() : null),
                _MenuItem('删除', Icons.delete,
                    () => provider.setEditMode(EditMode.delete)),
              ],
            ),

            // 视图菜单，对应原Android的menuView
            _buildMenuButton(
              context,
              '视图',
              [
                _MenuItem(
                  provider.showGrid ? '隐藏网格' : '显示网格',
                  provider.showGrid ? Icons.grid_off : Icons.grid_on,
                  () => provider.toggleGrid(),
                ),
                _MenuItem(
                  provider.showRuler ? '隐藏标尺' : '显示标尺',
                  provider.showRuler ? Icons.straighten : Icons.straighten,
                  () => provider.toggleRuler(),
                ),
                _MenuItem('放大', Icons.zoom_in, () => provider.zoomIn()),
                _MenuItem('缩小', Icons.zoom_out, () => provider.zoomOut()),
              ],
            ),

            // 地图菜单，对应原Android的menuMap
            _buildMenuButton(
              context,
              '地图',
              [
                _MenuItem('调整地图大小', Icons.settings,
                    () => _showResizeMapDialog(context)),
              ],
            ),

            // 图层菜单，对应原Android的menuC
            _buildMenuButton(
              context,
              '图层',
              [
                _MenuItem(
                    '添加图层', Icons.add_box, () => _showAddLayerDialog(context)),
                _MenuItem('添加对象层', Icons.category,
                    () => _showAddObjectLayerDialog(context)),
                _MenuItem('切换图层', Icons.layers,
                    () => _showLayerSelectDialog(context)),
                _MenuItem(
                    _showLayerPanel ? '隐藏图层面板' : '显示图层面板',
                    Icons.layers,
                    () => setState(() {
                          _showLayerPanel = !_showLayerPanel;
                        })),
                _MenuItem('隐藏/显示当前图层', Icons.visibility,
                    () => provider.toggleLayerVisibility()),
                _MenuItem('删除图层', Icons.delete_forever,
                    () => _deleteCurrentLayer(context, provider)),
                _MenuItem(
                    '重命名图层', Icons.edit, () => _showRenameLayerDialog(context)),
              ],
            ),

            const SizedBox(width: 16),

            // 编辑模式切换，对应原Android的mapMode
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 8),
              child: ElevatedButton.icon(
                onPressed: () => _toggleEditMode(provider),
                icon: Icon(
                  provider.editMode == EditMode.edit
                      ? Icons.visibility
                      : Icons.edit,
                  size: 16,
                ),
                label: Text(
                  provider.editMode == EditMode.edit ? '查看模式' : '编辑模式',
                  style: const TextStyle(fontSize: 12),
                ),
                style: ElevatedButton.styleFrom(
                  backgroundColor: provider.editMode == EditMode.edit
                      ? Colors.orange[100]
                      : Colors.blue[100],
                ),
              ),
            ),

            const SizedBox(width: 8),

            // 更多菜单，对应原Android的menuMore
            _buildMenuButton(
              context,
              '更多',
              [
                _MenuItem('帮助', Icons.help, () => _showHelp(context)),
                _MenuItem('关于', Icons.info, () => _showAbout(context)),
                _MenuItem(
                    '检查更新', Icons.system_update, () => _checkUpdate(context)),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildSelectedTilePreview(MapEditorProvider provider) {
    final selectedTileId = provider.selectedTileId;

    if (selectedTileId == 0) {
      return const Icon(Icons.clear, color: Colors.grey);
    }

    // 基础图块颜色
    const tileColors = [
      Colors.transparent,
      Colors.brown,
      Colors.green,
      Colors.blue,
      Colors.grey,
      Colors.red,
      Colors.yellow,
      Colors.purple,
      Colors.orange,
      Colors.cyan,
    ];

    if (selectedTileId < tileColors.length) {
      return Container(
        decoration: BoxDecoration(
          color: tileColors[selectedTileId],
          borderRadius: BorderRadius.circular(2),
        ),
      );
    }

    return Container(
      decoration: BoxDecoration(
        color: Colors.grey[200],
        borderRadius: BorderRadius.circular(2),
      ),
      child: Center(
        child: Text(
          selectedTileId.toString(),
          style: const TextStyle(fontSize: 8),
        ),
      ),
    );
  }

  Widget _buildMenuButton(
      BuildContext context, String title, List<_MenuItem> items) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 4),
      child: PopupMenuButton<VoidCallback?>(
        child: Container(
          padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
          decoration: BoxDecoration(
            color: Colors.grey[200],
            borderRadius: BorderRadius.circular(4),
          ),
          child: Text(
            title,
            style: const TextStyle(fontSize: 12),
          ),
        ),
        itemBuilder: (context) => items.map((item) {
          return PopupMenuItem<VoidCallback?>(
            value: item.onTap,
            enabled: item.onTap != null,
            child: Row(
              children: [
                Icon(item.icon, size: 16),
                const SizedBox(width: 8),
                Text(item.title, style: const TextStyle(fontSize: 12)),
              ],
            ),
          );
        }).toList(),
        onSelected: (callback) => callback?.call(),
      ),
    );
  }

  void _toggleEditMode(MapEditorProvider provider) {
    if (provider.editMode == EditMode.edit) {
      provider.setEditMode(EditMode.view);
    } else {
      provider.setEditMode(EditMode.edit);
    }
  }

  void _showNewMapDialog(BuildContext context) {
    final filenameController = TextEditingController(text: 'untitled.tmx');
    final widthController = TextEditingController(text: '100');
    final heightController = TextEditingController(text: '100');
    final tileWidthController = TextEditingController(text: '32');
    final tileHeightController = TextEditingController(text: '32');

    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('新建地图'),
        content: SizedBox(
          width: 400,
          child: SingleChildScrollView(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                // 地图文件名，对应Android的newmapEditText
                TextField(
                  controller: filenameController,
                  decoration: const InputDecoration(
                    labelText: '地图文件名',
                    border: OutlineInputBorder(),
                  ),
                ),
                const SizedBox(height: 16),

                // 地图尺寸行，对应Android布局
                Row(
                  children: [
                    Expanded(
                      child: TextField(
                        controller: widthController,
                        decoration: const InputDecoration(
                          labelText: '地图宽度',
                          border: OutlineInputBorder(),
                        ),
                        keyboardType: TextInputType.number,
                      ),
                    ),
                    const SizedBox(width: 16),
                    Expanded(
                      child: TextField(
                        controller: heightController,
                        decoration: const InputDecoration(
                          labelText: '地图高度',
                          border: OutlineInputBorder(),
                        ),
                        keyboardType: TextInputType.number,
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 16),

                // 图块尺寸行，对应Android布局
                Row(
                  children: [
                    Expanded(
                      child: TextField(
                        controller: tileWidthController,
                        decoration: const InputDecoration(
                          labelText: '图块宽度',
                          border: OutlineInputBorder(),
                        ),
                        keyboardType: TextInputType.number,
                      ),
                    ),
                    const SizedBox(width: 16),
                    Expanded(
                      child: TextField(
                        controller: tileHeightController,
                        decoration: const InputDecoration(
                          labelText: '图块高度',
                          border: OutlineInputBorder(),
                        ),
                        keyboardType: TextInputType.number,
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              final width = int.tryParse(widthController.text) ?? 100;
              final height = int.tryParse(heightController.text) ?? 100;
              final tileWidth = int.tryParse(tileWidthController.text) ?? 32;
              final tileHeight = int.tryParse(tileHeightController.text) ?? 32;

              final provider =
                  Provider.of<MapEditorProvider>(context, listen: false);
              provider.createNewMap(
                width: width,
                height: height,
                tileWidth: tileWidth,
                tileHeight: tileHeight,
              );

              Navigator.of(context).pop();
            },
            child: const Text('创建'),
          ),
        ],
      ),
    );
  }

  // 打开地图文件
  void _openMap(BuildContext context, MapEditorProvider provider) async {
    final messenger = ScaffoldMessenger.of(context);
    try {
      final map = await FileService.openMapFile();
      if (map != null) {
        // 这里应该设置文件路径，但需要修改provider来支持
        if (mounted) {
          messenger.showSnackBar(
            const SnackBar(content: Text('地图文件打开成功')),
          );
        }
      }
    } catch (e) {
      if (mounted) {
        messenger.showSnackBar(
          SnackBar(content: Text('打开失败: $e')),
        );
      }
    }
  }

  // 保存地图文件
  void _saveMap(BuildContext context, MapEditorProvider provider) async {
    final messenger = ScaffoldMessenger.of(context);
    if (!provider.hasMap) {
      messenger.showSnackBar(
        const SnackBar(content: Text('没有可保存的地图')),
      );
      return;
    }

    try {
      await provider.saveMap();
      if (mounted) {
        messenger.showSnackBar(
          const SnackBar(content: Text('地图保存成功')),
        );
      }
    } catch (e) {
      // 如果没有文件路径，显示另存为对话框
      if (mounted) {
        _saveAsMap(context, provider);
      }
    }
  }

  // 另存为地图文件
  void _saveAsMap(BuildContext context, MapEditorProvider provider) async {
    if (!provider.hasMap) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('没有可保存的地图')),
      );
      return;
    }

    final nameController = TextEditingController(text: 'untitled');

    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('另存为'),
        content: TextField(
          controller: nameController,
          decoration: const InputDecoration(
            labelText: '文件名（不包含扩展名）',
            border: OutlineInputBorder(),
          ),
          autofocus: true,
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () async {
              final navigator = Navigator.of(context);
              final messenger = ScaffoldMessenger.of(context);
              navigator.pop();
              try {
                final filePath = await FileService.saveAsMapFile(
                  provider.currentMap!,
                  nameController.text,
                );
                if (filePath != null && mounted) {
                  messenger.showSnackBar(
                    SnackBar(
                        content:
                            Text('保存成功: ${FileService.getFileName(filePath)}')),
                  );
                }
              } catch (e) {
                if (mounted) {
                  messenger.showSnackBar(
                    SnackBar(content: Text('保存失败: $e')),
                  );
                }
              }
            },
            child: const Text('保存'),
          ),
        ],
      ),
    );
  }

  // 导出为文本
  void _exportAsText(BuildContext context, MapEditorProvider provider) async {
    if (!provider.hasMap) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('没有可导出的地图')),
      );
      return;
    }

    final nameController = TextEditingController(text: 'map_export.txt');

    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('导出为文本'),
        content: TextField(
          controller: nameController,
          decoration: const InputDecoration(
            labelText: '文件名',
            border: OutlineInputBorder(),
          ),
          autofocus: true,
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () async {
              final navigator = Navigator.of(context);
              final messenger = ScaffoldMessenger.of(context);
              navigator.pop();
              try {
                final defaultDir = await FileService.getDefaultMapDirectory();
                final filePath = '$defaultDir/${nameController.text}';
                await FileService.exportAsText(provider.currentMap!, filePath);
                if (mounted) {
                  messenger.showSnackBar(
                    SnackBar(content: Text('导出成功: $filePath')),
                  );
                }
              } catch (e) {
                if (mounted) {
                  messenger.showSnackBar(
                    SnackBar(content: Text('导出失败: $e')),
                  );
                }
              }
            },
            child: const Text('导出'),
          ),
        ],
      ),
    );
  }

  // 导出为数组
  void _exportAsArray(BuildContext context, MapEditorProvider provider) async {
    if (!provider.hasMap) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('没有可导出的地图')),
      );
      return;
    }

    final nameController = TextEditingController(text: 'map_array.c');

    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('导出为数组'),
        content: TextField(
          controller: nameController,
          decoration: const InputDecoration(
            labelText: '文件名',
            border: OutlineInputBorder(),
          ),
          autofocus: true,
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () async {
              final navigator = Navigator.of(context);
              final messenger = ScaffoldMessenger.of(context);
              navigator.pop();
              try {
                final defaultDir = await FileService.getDefaultMapDirectory();
                final filePath = '$defaultDir/${nameController.text}';
                await FileService.exportAsArray(provider.currentMap!, filePath);
                if (mounted) {
                  messenger.showSnackBar(
                    SnackBar(content: Text('导出成功: $filePath')),
                  );
                }
              } catch (e) {
                if (mounted) {
                  messenger.showSnackBar(
                    SnackBar(content: Text('导出失败: $e')),
                  );
                }
              }
            },
            child: const Text('导出'),
          ),
        ],
      ),
    );
  }

  void _showResizeMapDialog(BuildContext context) {
    final provider = Provider.of<MapEditorProvider>(context, listen: false);
    if (!provider.hasMap) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('没有打开的地图')),
      );
      return;
    }

    final currentMap = provider.currentMap!;
    final widthController =
        TextEditingController(text: currentMap.width.toString());
    final heightController =
        TextEditingController(text: currentMap.height.toString());
    final tileWidthController =
        TextEditingController(text: currentMap.tileWidth.toString());
    final tileHeightController =
        TextEditingController(text: currentMap.tileHeight.toString());

    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('地图设置'),
        content: SizedBox(
          width: 400,
          child: SingleChildScrollView(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                // 图块尺寸设置，对应Android的blockWidth/blockHeight
                const Text(
                  '图块尺寸',
                  style: TextStyle(fontWeight: FontWeight.bold),
                ),
                const SizedBox(height: 8),
                Row(
                  children: [
                    Expanded(
                      child: TextField(
                        controller: tileWidthController,
                        decoration: const InputDecoration(
                          labelText: '块宽度',
                          border: OutlineInputBorder(),
                        ),
                        keyboardType: TextInputType.number,
                      ),
                    ),
                    const SizedBox(width: 16),
                    Expanded(
                      child: TextField(
                        controller: tileHeightController,
                        decoration: const InputDecoration(
                          labelText: '块高度',
                          border: OutlineInputBorder(),
                        ),
                        keyboardType: TextInputType.number,
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 24),

                // 地图尺寸设置，对应Android的mapWidth/mapHeight
                const Text(
                  '地图尺寸',
                  style: TextStyle(fontWeight: FontWeight.bold),
                ),
                const SizedBox(height: 8),
                Row(
                  children: [
                    Expanded(
                      child: TextField(
                        controller: widthController,
                        decoration: const InputDecoration(
                          labelText: '地图宽度',
                          border: OutlineInputBorder(),
                        ),
                        keyboardType: TextInputType.number,
                      ),
                    ),
                    const SizedBox(width: 16),
                    Expanded(
                      child: TextField(
                        controller: heightController,
                        decoration: const InputDecoration(
                          labelText: '地图高度',
                          border: OutlineInputBorder(),
                        ),
                        keyboardType: TextInputType.number,
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              final newWidth =
                  int.tryParse(widthController.text) ?? currentMap.width;
              final newHeight =
                  int.tryParse(heightController.text) ?? currentMap.height;
              final newTileWidth = int.tryParse(tileWidthController.text) ??
                  currentMap.tileWidth;
              final newTileHeight = int.tryParse(tileHeightController.text) ??
                  currentMap.tileHeight;

              // 应用地图大小调整
              provider.resizeMap(newWidth, newHeight);

              // TODO: 实现图块大小调整
              // provider.resizeTiles(newTileWidth, newTileHeight);

              Navigator.of(context).pop();
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(content: Text('地图设置已应用')),
              );
            },
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }

  void _showAddLayerDialog(BuildContext context) {
    final provider = Provider.of<MapEditorProvider>(context, listen: false);
    if (!provider.hasMap) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('没有打开的地图')),
      );
      return;
    }

    final nameController = TextEditingController(text: '新图层');

    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('创建新图层'),
        content: TextField(
          controller: nameController,
          decoration: const InputDecoration(
            labelText: '图层名称',
            border: OutlineInputBorder(),
          ),
          autofocus: true,
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              provider.addLayer(nameController.text);
              Navigator.of(context).pop();
              ScaffoldMessenger.of(context).showSnackBar(
                SnackBar(content: Text('图层 "${nameController.text}" 已创建')),
              );
            },
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }

  void _showAddObjectLayerDialog(BuildContext context) {
    final provider = Provider.of<MapEditorProvider>(context, listen: false);
    if (!provider.hasMap) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('没有打开的地图')),
      );
      return;
    }

    final nameController = TextEditingController(text: '新对象层');

    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('创建新对象层'),
        content: TextField(
          controller: nameController,
          decoration: const InputDecoration(
            labelText: '对象层名称',
            border: OutlineInputBorder(),
          ),
          autofocus: true,
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              provider.addLayer(nameController.text, isObjectLayer: true);
              Navigator.of(context).pop();
              ScaffoldMessenger.of(context).showSnackBar(
                SnackBar(content: Text('对象层 "${nameController.text}" 已创建')),
              );
            },
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }

  void _showLayerSelectDialog(BuildContext context) {
    final provider = Provider.of<MapEditorProvider>(context, listen: false);
    if (!provider.hasMap) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('没有打开的地图')),
      );
      return;
    }

    final layers = provider.currentMap!.layers;

    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('选择图层'),
        content: SizedBox(
          width: 300,
          height: 400,
          child: ListView.builder(
            itemCount: layers.length,
            itemBuilder: (context, index) {
              final layer = layers[index];
              final isSelected = index == provider.currentLayerIndex;

              return ListTile(
                leading: Container(
                  width: 24,
                  height: 24,
                  decoration: BoxDecoration(
                    color: layer.isObjectLayer
                        ? Colors.orange[100]
                        : Colors.blue[100],
                    border: Border.all(color: Colors.grey[400]!),
                    borderRadius: BorderRadius.circular(2),
                  ),
                  child: Icon(
                    layer.isObjectLayer ? Icons.category : Icons.grid_on,
                    size: 16,
                    color: layer.isObjectLayer
                        ? Colors.orange[700]
                        : Colors.blue[700],
                  ),
                ),
                title: Text(layer.name),
                subtitle: Text('${layer.isObjectLayer ? "对象层" : "图块层"} - '
                    '透明度: ${(layer.opacity * 100).toInt()}%'),
                trailing: Icon(
                  layer.visible ? Icons.visibility : Icons.visibility_off,
                  color: layer.visible ? Colors.blue : Colors.grey,
                ),
                selected: isSelected,
                onTap: () {
                  provider.selectLayer(index);
                  Navigator.of(context).pop();
                },
              );
            },
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('关闭'),
          ),
        ],
      ),
    );
  }

  void _deleteCurrentLayer(BuildContext context, MapEditorProvider provider) {
    if (!provider.hasMap) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('没有打开的地图')),
      );
      return;
    }

    if (provider.currentMap!.layers.length <= 1) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('至少需要保留一个图层')),
      );
      return;
    }

    final currentLayer =
        provider.currentMap!.layers[provider.currentLayerIndex];

    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('删除图层'),
        content: Text('确定要删除图层 "${currentLayer.name}" 吗？此操作不可撤销。'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              provider.deleteCurrentLayer();
              Navigator.of(context).pop();
              ScaffoldMessenger.of(context).showSnackBar(
                SnackBar(content: Text('图层 "${currentLayer.name}" 已删除')),
              );
            },
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.red,
              foregroundColor: Colors.white,
            ),
            child: const Text('删除'),
          ),
        ],
      ),
    );
  }

  void _showRenameLayerDialog(BuildContext context) {
    final provider = Provider.of<MapEditorProvider>(context, listen: false);
    if (!provider.hasMap) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('没有打开的地图')),
      );
      return;
    }

    final currentLayer =
        provider.currentMap!.layers[provider.currentLayerIndex];
    final nameController = TextEditingController(text: currentLayer.name);

    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('重命名图层'),
        content: TextField(
          controller: nameController,
          decoration: const InputDecoration(
            labelText: '新名称',
            border: OutlineInputBorder(),
          ),
          autofocus: true,
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              provider.renameLayer(
                  provider.currentLayerIndex, nameController.text);
              Navigator.of(context).pop();
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(content: Text('图层重命名成功')),
              );
            },
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }

  void _showHelp(BuildContext context) {
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(content: Text('帮助功能待实现')),
    );
  }

  void _showAbout(BuildContext context) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('关于'),
        content: const Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text('地图编辑器 Flutter 版本'),
            Text('版本: 1.0.0'),
            SizedBox(height: 16),
            Text('一个功能完整的瓦片地图编辑器'),
            Text('支持TMX格式的地图文件'),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }

  void _checkUpdate(BuildContext context) {
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(content: Text('检查更新功能待实现')),
    );
  }
}

class _MenuItem {
  final String title;
  final IconData icon;
  final VoidCallback? onTap;

  _MenuItem(this.title, this.icon, this.onTap);
}
